<?php
namespace Api\Event;

/**
 * 新闻评论
 * @author liubo <liubo@ilongyuan.com.cn>
 */
class NewsCommentsEvent extends BaseEvent
{

    public function add($news_id, $uid, $content)
    {
        $news = service('News')->where(['id' => $news_id, 'type' => 0])->find();
        if (empty($news)) {
            return false;
        }
        // 过滤敏感词
        event('Sensitive')->censor($content);

        if (empty($uid)) {
            $user = [
                'id' => 0,
                'nickname' => getVisitorName(),
            ];
        } else {
            $user = service('Users')->find($uid);
        }
        if (empty($user)) {
            return false;
        }
        $comment = [
            'uid' => $user['id'],
            'nickname' => $user['nickname'],
            'news_id' => $news_id,
            'content' => $content,
        ];
        return service('NewsComments')->addComment($comment);
    }

    public function get($news_id, $user_detail = false, $p = 1, $limit = 10, &$total)
    {
        $condition = [
            'news_id' => $news_id,
            'status'   => ['egt', 0]
        ];
        $total = $this->count($news_id);
        $res = service('NewsComments')->getByPager($condition, $p, $limit);

        $list = [];
        foreach ($res as $key => $value) {
            unset($value['_id']);
            if ($user_detail) {
                if ($value['uid'] > 0)
                {
                    $user = event('User')->info($value['uid']);
                    $value['avatar'] = $user['avatar'];
                }else{
                    $user = [
                        'id' => 0,
                        'nickname' => $value['nickname'],
                    ];
                }
                $user && $value['user'] = $user;
            }
 
            $list[] = $value;
        }
        return $list;
    }

    public function count($news_id)
    {
        $condition = [
            'news_id' => $news_id,
            'status'   => ['egt', 0]
        ];
        $total = service('NewsComments')->where($condition)->count();
        return intval($total);
    }
}